//
// Created by liufenglin on 20-4-7.
//

#include "config.h"
#include "fileUtil.h"
#include "string.h"
#include <stdlib.h>
#include <stdio.h>

char *csvFile=NULL;
char *csvColumn=NULL;
char *mysqlHost=NULL;
unsigned int mysqlPort=3306;
char *mysqlUser=NULL;
char *mysqlPassword=NULL;
char *mysqlDB=NULL;
char *mysqlTable=NULL;
int threads=1;

void updateFiledValue(char *fieldName,char *value){
    if(strcmp(fieldName,"csvFile")==0){
        strcpy(csvFile,value);
    } else if(strcmp(fieldName,"csvColumn")==0){
        strcpy(csvColumn,value);
    }else if(strcmp(fieldName,"mysqlHost")==0){
        strcpy(mysqlHost,value);
    }else if(strcmp(fieldName,"mysqlPort")==0){
         mysqlPort = atoi(value);
    }else if(strcmp(fieldName,"mysqlUser")==0){
        strcpy(mysqlUser,value);
    }else if(strcmp(fieldName,"mysqlPassword")==0){
        strcpy(mysqlPassword,value);
    }else if(strcmp(fieldName,"mysqlDB")==0){
        strcpy(mysqlDB,value);
    }else if(strcmp(fieldName,"mysqlTable")==0){
        strcpy(mysqlTable,value);
    }else if(strcmp(fieldName,"threads")==0){
        threads = atoi(value);
    }
}

void parseLine(char *line){

    int len = strlen(line);
    if(len>0&&line[len-1]=='\n'){
        line[len-1]='\0';
    }
    int token = '=';
    char key[20];
    char value[200];
    char *v = strchr(line, token);
    if (v != NULL && v != line) {
        *v = '\0';
        strcpy(key, line);
        strcpy(value, v + 1);
        updateFiledValue(key,value);
    }
}

void initConfig(){
    csvFile = calloc(200,sizeof(char));
    csvColumn= calloc(200,sizeof(char));
    mysqlHost= calloc(20,sizeof(char));
    mysqlPort= 3306;
    mysqlUser= calloc(20,sizeof(char));
    mysqlPassword= calloc(20,sizeof(char));
    mysqlDB= calloc(20,sizeof(char));
    mysqlTable= calloc(20,sizeof(char));
    threads = 1;
}

void parseConfig(int argc, char *argv[]){
    initConfig();
    char configFile[200] = "conf.conf";
    if (argc > 1) {
        strcpy(configFile, argv[1]);
    }
    printf("use config:%s\n", configFile);
    readFile(configFile,parseLine);
#ifdef DEBUG
    showConfig();
#endif
}

void showConfig(){
    printf("csv:%s\n",csvFile);
    printf("column:%s\n",csvColumn);
    printf("host:%s\n",mysqlHost);
    printf("port:%d\n",mysqlPort);
    printf("user:%s\n",mysqlUser);
    printf("password:%s\n",mysqlPassword);
    printf("db:%s\n",mysqlDB);
    printf("table:%s\n",mysqlTable);

}

void freeConfig(){
    free(csvFile);
    free(csvColumn);
    free(mysqlHost);
    free(mysqlUser);
    free(mysqlPassword);
    free(mysqlDB);
    free(mysqlTable);
}


